package com.minelx.woods.data;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoIterable;
import org.bson.Document;
import org.bson.types.ObjectId;

import java.util.LinkedList;
import java.util.List;

import static java.util.Collections.emptyList;

public class Reviews {

	private final MongoCollection<Document> reviewsCollection;

	public Reviews(MongoCollection<Document> reviewsCollection) {
		this.reviewsCollection = reviewsCollection;
	}

	public List<Review> range(int offset, int length) {
		MongoIterable<Review> result = reviewsCollection.find(new Document())
				.skip(offset).limit(length)
				.projection(new Document("_id", "1"))
				.map(document -> id(document.getObjectId("_id").toString()));
		return result.into(new LinkedList<>());
	}

	public Review createReview(String submitterId, String name, String taskId, List<String> reviewers) {
		Document inserted = new Document();
		ObjectId reviewId = new ObjectId();
		inserted.put("_id", reviewId);
		inserted.put("name", name);
		inserted.put("taskId", taskId);
		inserted.put("submitterId", submitterId);
		inserted.put("approved", emptyList());
		inserted.put("reviewers", reviewers);
		inserted.put("isRejected", false);
		reviewsCollection.insertOne(inserted);
		return id(reviewId.toString());
	}

	public void removeAll() {
		reviewsCollection.deleteMany(new Document());
	}

	public Review id(String id) {
		return new Review(reviewsCollection, id);
	}
}
